const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const logger = require('koa-logger')

const router = require('./router')

const log4js = require('./utils/log4j')
const util = require('./utils/util')

// 引入托管静态资源
const static = require('koa-static')
const path = require('path')


const { koaBody } = require('koa-body');

app.use(koaBody({
  multipart: true, // 支持文件上传
  // encoding: 'gzip',
  formidable: {
    uploadDir: path.join(__dirname, 'public/uploads/'), // 设置文件上传目录
    keepExtensions: true,    // 保持文件的后缀
    maxFieldsSize: 2 * 1024 * 1024, // 文件上传大小
    onError(err) {
      console.log(err)
    },
    onFileBegin: (name, file) => { // 文件上传前的设置
      // console.log(`name: ${name}`);
      // console.log(file);
      file.path = `public/uploads/${name}`
    },
  }
}));

onerror(app)

app.use(json())
app.use(logger())


app.use(static(path.join(__dirname + '/public')))

// 跨域
const cors = require('koa-cors');
app.use(cors())

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  console.log(JSON.stringify(ctx.request.body) == {}, JSON.stringify(ctx.request.query) == {}, 1);
  log4js.info(`post params:${JSON.stringify(ctx.request.body)}`);
  log4js.info(`get params:${JSON.stringify(ctx.request.query)}`);
  await next()
})

app.use(router.routes(), router.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  log4js.error(`${err}`)
});

// app.listen(8080, () => {
//   console.log('服务器启动');
// })
app.listen(3030);

module.exports = app
